package cn.err0r.android.shsmead;

import java.util.ArrayList;
import java.util.Calendar;

import org.json.JSONArray;
import org.json.JSONObject;

import cn.err0r.android.shsmead.service.UpdateService;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.baidu.mobstat.StatService;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class Main extends BaseActivity {

	private TextView title;
	String url = "http://www.smead.sh.cn/FlImageServlet?closedate=";
	String date ="";
	private Button btnViewimg;
	private ListView roadList;
	private ArrayList<String> roadinfo;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mainlayout);
		StatService.setAppKey("347545bd72");
		initpage();
	}
	
	void initpage(){
		AQuery aq = new AQuery(this);
		title = (TextView) findViewById(R.id.textView2);
		Calendar now = Calendar.getInstance();
		String month = String.valueOf(now.get(Calendar.MONTH) + 1);
		int day = now.get(Calendar.DAY_OF_MONTH);
		int year = now.get(Calendar.YEAR);
		int hour = now.get(Calendar.HOUR_OF_DAY);
		month = month.length() == 1 ? "0"+month : month;
		if(hour < 5)
			day = day - 1;
		if(day == 0){
			switch (now.get(Calendar.MONTH)) {
			case 1:
			case 3:
			case 5:
			case 7:
			case 8:
			case 10:
			case 12:
				day = 31;
				break;
			case 2:
				day = 28;
			default:
				day = 30;
				break;
			}
		}
		date = "" + (year + "-" + month + "-" +day);
		title.setText(date + "上海快速道路封路计划");
		btnViewimg = (Button)findViewById(R.id.button1);
		btnViewimg.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				StatService.onEvent(Main.this, "2", "加载图片路况", 1);
				Intent intent = new Intent(Main.this, IMageShow.class);
				intent.putExtra("img", url+date);
				startActivity(intent);
				overridePendingTransition(R.anim.activity_left_in, R.anim.activity_right_out);
			}
		});
		roadList = (ListView)findViewById(R.id.listView1);
		StatService.onEventDuration(Main.this,"1", "loadtextroadinfo", 100);
		openLoading("正在加载本日封路信息");
		aq.ajax("http://www.err0r.cn/api/df.php", JSONObject.class, acsreach);
		aq.ajax("http://www.err0r.cn/api/ckupdata.php", JSONObject.class, acckupdata);
		
	}
	AjaxCallback<JSONObject> acsreach = new AjaxCallback<JSONObject>(){

		@Override
		public void callback(String url, JSONObject object, AjaxStatus status) {
			// TODO Auto-generated method stub
			super.callback(url, object, status);
			closeLoading();
			if(object != null){
            	try {
                    if(status.getCode() == 200){
                    	StatService.onEventEnd(Main.this, "1","loadtextroadinfo");
                    	Log.i("sreach", object.toString());
                    	JSONArray titles = object.getJSONArray("titles");
                    	roadinfo = new ArrayList<String>();
                    	for (int i = 0; i < titles.length(); i++) {
                    		if(!titles.getJSONObject(i).getString("title").trim().equals("&nbsp;"))
                    			roadinfo.add(titles.getJSONObject(i).getString("title"));
						}
                    	RoadinfoAdpter adapter = new RoadinfoAdpter(Main.this,roadinfo);
                    	roadList.setAdapter(adapter);
                    }
            	}catch(Exception e){
            		StatService.onEvent(Main.this, "3", "加载文字异常", 1);
            	}
			}
		}
		
	};

	AjaxCallback<JSONObject> acckupdata = new AjaxCallback<JSONObject>(){

		/**
		 * 检查更新版本
		 */
		@SuppressWarnings("unused")
		public void checkVersion(int serverVersion){
		 
		    try {
				if(Main.this.getPackageManager().getPackageInfo(getPackageName(),0).versionCode < serverVersion){
				    //发现新版本，提示用户更新
				    AlertDialog.Builder alert = new AlertDialog.Builder(Main.this);
				    alert.setTitle("软件升级")
				         .setMessage("发现新版本,建议立即更新使用.")
				         .setPositiveButton("更新", new DialogInterface.OnClickListener() {
				             public void onClick(DialogInterface dialog, int which) {
				                 //开启更新服务UpdateService
				                 //这里为了把update更好模块化，可以传一些updateService依赖的值
				                 //如布局ID，资源ID，动态获取的标题,这里以app_name为例
		                     Intent updateIntent =new Intent(Main.this, UpdateService.class);
		                     updateIntent.putExtra("titleId",R.string.app_name);
		                     startService(updateIntent);
				             }
				         })
				         .setNegativeButton("取消",new DialogInterface.OnClickListener(){
				             public void onClick(DialogInterface dialog, int which) {
				                 dialog.dismiss();
				             }
				         });
				    alert.create().show();
				}else{
				    //清理工作，略去
				    //cheanUpdateFile()
				}
			} catch (NameNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		@Override
		public void callback(String url, JSONObject object, AjaxStatus status) {
			// TODO Auto-generated method stub
			super.callback(url, object, status);
			if(object != null){
            	try {
                    if(status.getCode() == 200){
                    	Log.i("acckupdata", object.toString());
                    	checkVersion(object.getInt("ver"));
                    	
                    }
            	}catch(Exception e){
            	}
			}
		}
		
	};

}
